"use client"

import { useState, useEffect } from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Label
} from "@/components/ui/label"
import {
  Textarea
} from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Package,
  Plus,
  Edit,
  Trash2,
  Eye,
  Upload,
  Download,
  Calendar,
  User,
  AlertCircle,
  CheckCircle,
  MoreHorizontal,
  Image as ImageIcon
} from "lucide-react"

interface Sample {
  id: string
  projectId: string
  sampleName: string
  sampleCode: string
  sampleType: string
  description: string
  quantity: number
  unit: string
  status: string
  location: string
  receivedDate: string
  testDate: string
  completedDate: string
  testResults: string
  images: string[]
  notes: string
  createdBy: string
  createdAt: string
  updatedAt: string
}

interface SampleManagementProps {
  projectId: string
  projectName: string
}

export function SampleManagement({ projectId, projectName }: SampleManagementProps) {
  const [samples, setSamples] = useState<Sample[]>([])
  const [loading, setLoading] = useState(true)
  const [editingSample, setEditingSample] = useState<Sample | null>(null)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [uploading, setUploading] = useState(false)

  useEffect(() => {
    fetchSamples()
  }, [projectId])

  const fetchSamples = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/projects/${projectId}/samples`)
      if (response.ok) {
        const data = await response.json()
        // 如果返回的是数组，直接使用；如果是对象，提取samples属性
        const samplesArray = Array.isArray(data) ? data : (data.samples || [])
        setSamples(samplesArray)
      }
    } catch (error) {
      console.error('Error fetching samples:', error)
      // 设置一些默认的示例数据
      setSamples([])
    } finally {
      setLoading(false)
    }
  }

  const getStatusColor = (status: string) => {
    const statusColors: Record<string, string> = {
      'PENDING': 'bg-yellow-100 text-yellow-800',
      'RECEIVED': 'bg-blue-100 text-blue-800',
      'TESTING': 'bg-purple-100 text-purple-800',
      'COMPLETED': 'bg-green-100 text-green-800',
      'FAILED': 'bg-red-100 text-red-800',
      'CANCELLED': 'bg-gray-100 text-gray-800'
    }
    return statusColors[status] || 'bg-gray-100 text-gray-800'
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'PENDING':
        return <AlertCircle className="h-4 w-4" />
      case 'COMPLETED':
        return <CheckCircle className="h-4 w-4" />
      default:
        return <Package className="h-4 w-4" />
    }
  }

  const handleCreateSample = async (formData: any) => {
    try {
      const response = await fetch(`/api/projects/${projectId}/samples`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...formData,
          projectId,
          createdBy: "user-1" // 临时用户ID
        })
      })

      if (response.ok) {
        await fetchSamples()
        setDialogOpen(false)
        setEditingSample(null)
      }
    } catch (error) {
      console.error('Error creating sample:', error)
    }
  }

  const handleUpdateSample = async (formData: any) => {
    if (!editingSample) return

    try {
      const response = await fetch(`/api/projects/${projectId}/samples/${editingSample.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      })

      if (response.ok) {
        await fetchSamples()
        setDialogOpen(false)
        setEditingSample(null)
      }
    } catch (error) {
      console.error('Error updating sample:', error)
    }
  }

  const handleDeleteSample = async (sampleId: string) => {
    if (!confirm('确定要删除这个样品吗？')) return

    try {
      const response = await fetch(`/api/projects/${projectId}/samples/${sampleId}`, {
        method: 'DELETE'
      })

      if (response.ok) {
        await fetchSamples()
      }
    } catch (error) {
      console.error('Error deleting sample:', error)
    }
  }

  const handleImageUpload = async (sampleId: string, files: FileList) => {
    setUploading(true)
    try {
      // 这里应该实现图片上传逻辑
      console.log('Uploading images for sample:', sampleId, files)
      // 模拟上传延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      await fetchSamples()
    } catch (error) {
      console.error('Error uploading images:', error)
    } finally {
      setUploading(false)
    }
  }

  const SampleForm = ({ sample, onSubmit }: { sample?: Sample; onSubmit: (data: any) => void }) => {
    const [formData, setFormData] = useState({
      sampleName: sample?.sampleName || "",
      sampleCode: sample?.sampleCode || "",
      sampleType: sample?.sampleType || "",
      description: sample?.description || "",
      quantity: sample?.quantity || 1,
      unit: sample?.unit || "个",
      status: sample?.status || "PENDING",
      location: sample?.location || "",
      receivedDate: sample?.receivedDate || "",
      testDate: sample?.testDate || "",
      completedDate: sample?.completedDate || "",
      testResults: sample?.testResults || "",
      notes: sample?.notes || ""
    })

    const handleSubmit = (e: React.FormEvent) => {
      e.preventDefault()
      onSubmit(formData)
    }

    return (
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="sampleName">样品名称 *</Label>
            <Input
              id="sampleName"
              value={formData.sampleName}
              onChange={(e) => setFormData(prev => ({ ...prev, sampleName: e.target.value }))}
              placeholder="输入样品名称"
              required
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="sampleCode">样品编码</Label>
            <Input
              id="sampleCode"
              value={formData.sampleCode}
              onChange={(e) => setFormData(prev => ({ ...prev, sampleCode: e.target.value }))}
              placeholder="输入样品编码"
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="sampleType">样品类型</Label>
            <Select value={formData.sampleType} onValueChange={(value) => setFormData(prev => ({ ...prev, sampleType: value }))}>
              <SelectTrigger>
                <SelectValue placeholder="选择样品类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="material">材料样品</SelectItem>
                <SelectItem value="product">产品样品</SelectItem>
                <SelectItem value="chemical">化学样品</SelectItem>
                <SelectItem value="biological">生物样品</SelectItem>
                <SelectItem value="other">其他</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="status">状态</Label>
            <Select value={formData.status} onValueChange={(value) => setFormData(prev => ({ ...prev, status: value }))}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="PENDING">待接收</SelectItem>
                <SelectItem value="RECEIVED">已接收</SelectItem>
                <SelectItem value="TESTING">测试中</SelectItem>
                <SelectItem value="COMPLETED">已完成</SelectItem>
                <SelectItem value="FAILED">测试失败</SelectItem>
                <SelectItem value="CANCELLED">已取消</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="quantity">数量</Label>
            <Input
              id="quantity"
              type="number"
              value={formData.quantity}
              onChange={(e) => setFormData(prev => ({ ...prev, quantity: parseInt(e.target.value) || 0 }))}
              placeholder="输入数量"
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="unit">单位</Label>
            <Select value={formData.unit} onValueChange={(value) => setFormData(prev => ({ ...prev, unit: value }))}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="个">个</SelectItem>
                <SelectItem value="件">件</SelectItem>
                <SelectItem value="批">批</SelectItem>
                <SelectItem value="kg">kg</SelectItem>
                <SelectItem value="g">g</SelectItem>
                <SelectItem value="L">L</SelectItem>
                <SelectItem value="mL">mL</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="location">存放位置</Label>
            <Input
              id="location"
              value={formData.location}
              onChange={(e) => setFormData(prev => ({ ...prev, location: e.target.value }))}
              placeholder="输入存放位置"
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="receivedDate">接收日期</Label>
            <Input
              id="receivedDate"
              type="date"
              value={formData.receivedDate}
              onChange={(e) => setFormData(prev => ({ ...prev, receivedDate: e.target.value }))}
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="testDate">测试日期</Label>
            <Input
              id="testDate"
              type="date"
              value={formData.testDate}
              onChange={(e) => setFormData(prev => ({ ...prev, testDate: e.target.value }))}
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="completedDate">完成日期</Label>
            <Input
              id="completedDate"
              type="date"
              value={formData.completedDate}
              onChange={(e) => setFormData(prev => ({ ...prev, completedDate: e.target.value }))}
            />
          </div>
        </div>
        
        <div className="space-y-2">
          <Label htmlFor="description">描述</Label>
          <Textarea
            id="description"
            value={formData.description}
            onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
            placeholder="输入样品描述"
            rows={3}
          />
        </div>
        
        <div className="space-y-2">
          <Label htmlFor="testResults">测试结果</Label>
          <Textarea
            id="testResults"
            value={formData.testResults}
            onChange={(e) => setFormData(prev => ({ ...prev, testResults: e.target.value }))}
            placeholder="输入测试结果"
            rows={3}
          />
        </div>
        
        <div className="space-y-2">
          <Label htmlFor="notes">备注</Label>
          <Textarea
            id="notes"
            value={formData.notes}
            onChange={(e) => setFormData(prev => ({ ...prev, notes: e.target.value }))}
            placeholder="输入备注信息"
            rows={2}
          />
        </div>
        
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>
            取消
          </Button>
          <Button type="submit">
            {sample ? "更新样品" : "创建样品"}
          </Button>
        </DialogFooter>
      </form>
    )
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-sm text-gray-500">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 顶部工具栏 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">样品管理</h2>
          <p className="text-gray-500">项目: {projectName}</p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button onClick={() => setEditingSample(null)}>
              <Plus className="mr-2 h-4 w-4" />
              添加样品
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {editingSample ? "编辑样品" : "添加新样品"}
              </DialogTitle>
              <DialogDescription>
                填写样品信息，{editingSample ? "更新" : "创建"}新的样品记录。
              </DialogDescription>
            </DialogHeader>
            <SampleForm
              sample={editingSample}
              onSubmit={editingSample ? handleUpdateSample : handleCreateSample}
            />
          </DialogContent>
        </Dialog>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">总样品数</p>
                <p className="text-2xl font-bold">{samples.length}</p>
              </div>
              <Package className="h-8 w-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">待接收</p>
                <p className="text-2xl font-bold">{samples.filter(s => s.status === 'PENDING').length}</p>
              </div>
              <AlertCircle className="h-8 w-8 text-yellow-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">测试中</p>
                <p className="text-2xl font-bold">{samples.filter(s => s.status === 'TESTING').length}</p>
              </div>
              <Package className="h-8 w-8 text-purple-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">已完成</p>
                <p className="text-2xl font-bold">{samples.filter(s => s.status === 'COMPLETED').length}</p>
              </div>
              <CheckCircle className="h-8 w-8 text-green-600" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 样品列表 */}
      <Card>
        <CardHeader>
          <CardTitle>样品列表</CardTitle>
        </CardHeader>
        <CardContent>
          {samples.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>样品信息</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>数量</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>接收日期</TableHead>
                  <TableHead>测试日期</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {samples.map((sample) => (
                  <TableRow key={sample.id}>
                    <TableCell>
                      <div>
                        <div className="font-medium">{sample.sampleName}</div>
                        {sample.sampleCode && (
                          <div className="text-sm text-gray-500">{sample.sampleCode}</div>
                        )}
                        {sample.description && (
                          <div className="text-sm text-gray-500">{sample.description}</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{sample.sampleType}</Badge>
                    </TableCell>
                    <TableCell>
                      <div>
                        <span className="font-medium">{sample.quantity}</span>
                        <span className="text-sm text-gray-500 ml-1">{sample.unit}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(sample.status)}>
                        <div className="flex items-center gap-1">
                          {getStatusIcon(sample.status)}
                          {sample.status}
                        </div>
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-gray-400" />
                        <span>{sample.receivedDate ? new Date(sample.receivedDate).toLocaleDateString() : '-'}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-gray-400" />
                        <span>{sample.testDate ? new Date(sample.testDate).toLocaleDateString() : '-'}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setEditingSample(sample)
                            setDialogOpen(true)
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteSample(sample.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                        
                        <input
                          type="file"
                          multiple
                          accept="image/*"
                          className="hidden"
                          id={`upload-${sample.id}`}
                          onChange={(e) => {
                            if (e.target.files) {
                              handleImageUpload(sample.id, e.target.files)
                            }
                          }}
                        />
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => document.getElementById(`upload-${sample.id}`)?.click()}
                          disabled={uploading}
                        >
                          <ImageIcon className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="text-center py-12">
              <Package className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无样品</h3>
              <p className="text-gray-500 mb-4">开始添加样品来管理项目的样品信息</p>
              <Button onClick={() => setDialogOpen(true)}>
                <Plus className="mr-2 h-4 w-4" />
                添加第一个样品
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}